import { Input, Space } from 'antd';
import { Table } from "antd";

import { Button, message, Popconfirm } from 'antd';
import './App6.css';
import { useState } from 'react';
import { useEffect } from 'react';
const { Search } = Input;
function App() {
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '年龄',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '住址',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '操作',
      dataIndex: 'do',
      key: 'do',
      render: (text, record) => {
        return (
          <Space size="middle">
            <Popconfirm title="确定删除吗?" onConfirm={() => onDelete(record.id)}>
              <a href="#">删除</a>
            </Popconfirm>
          </Space>
        )
      }
    }
  ];
  //初次加载页面，展示后端返回的所有数据
  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    fetch('http://localhost:3001/data')
      .then(res => res.json())
      .then(data => {
        setDataSource(data);
      })
  }, [])
  //删除数据
  function onDelete(id) {
    fetch(`http://localhost:3001/data/${id}`, {
      method: 'DELETE'
    })
      .then(res => res.json())
      .then(data => {
        if (data) {
          message.success('删除成功');
          setDataSource(dataSource.filter(item => item.id !== id));
        }
      })
      .catch(error => {
        message.error('删除失败');
        console.error('Error:', error);
      });
  }
  //获取到json的数据。并且将数据显示到表格中

  function onSearch(keyword) {
    fetch(`http://localhost:3001/data?name=${keyword}`)
      .then(res => res.json())
      .then(data => {
        setDataSource(data);
      })
      .catch(error => {
        console.error('Error:', error);
      });
  }
  return (
    <div className="container">
      <div className="seach-box">
        <Search
          placeholder='请输入关键词'
          enterButton="搜索"
          size="large"
          allowClear
          //点击搜索按钮，触发搜索事件
          onSearch={onSearch}

        />

      </div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={false}

      />
    </div>
  )
}
export default App;
